// pages/Medicine/Medicine.js
const util = require('../../utils/util.js');
let app=getApp();
Page({
  data: {
    minusStatusfrequency:'disable',
    minusStatusparticles:'disable',
    medicineList:[
      {
        name:'',
        frequency:0,
        particles:0,
      }
    ],
    medicineTitle:null,
    medicineTime:"选择",
    drugListRecordid:null
  },
  //减法
  bindMinus(e)
  {
    let tag = e.target.dataset.tag;
    let index = e.target.dataset.index ;
    if( this.data.medicineList[index][tag]===0)
    {
      if(tag==='frequency')
      {
        this.setData({
          minusStatusfrequency:'disable'
        })
      }
      else
      {
        this.setData({
          minusStatusparticles:'disable'
        })
      }
    }
    else
    {
      this.data.medicineList[index][tag] =this.data.medicineList[index][tag]-1;
      let array = this.data.medicineList;
    this.setData({
      medicineList:array
    })
    if( this.data.medicineList[index][tag]===0)
    {
      if(tag==='frequency')
      {
        this.setData({
          minusStatusfrequency:'disable'
        })
      }
      else
      {
        this.setData({
          minusStatusparticles:'disable'
        })
      }
    }
    }
  },
  //加法
  bindPlus(e){
   
    let tag = e.target.dataset.tag;
    if(tag==='frequency')
      {
        this.setData({
          minusStatusfrequency:'normal'
        })
      }
      else
      {
        this.setData({
          minusStatusparticles:'normal'
        })
      }
    let index = e.target.dataset.index ;
    this.data.medicineList[index][tag] =this.data.medicineList[index][tag]+1;
    let array = this.data.medicineList;
    this.setData({
      medicineList:array
    })
  },
  //删除药品
  deletePrice: function(e) {
    let that = this
    let index = e.target.dataset.index //数组下标
    let arrayLength = that.data.medicineList.length //数组长度
    let newArray = []
    if (arrayLength > 1) {
      //数组长度>1 才能删除
      for (let i = 0; i < arrayLength; i++) {
        if (i !== index) {
          newArray.push(that.data.medicineList[i])
        }
      }
      that.setData({
        medicineList: newArray
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '必须设置一个药品',
      })
    }
  },

  //新增药品
  addNewMedicine()
  {
    let that=this;
    let newArray={
      name:'',
      frequency:0,
      particles:0,
    }
    this.setData({
      medicineList:this.data.medicineList.concat(newArray)
    })
  },
  //获取值
  setInputvalue: function(e) {
    let index = e.target.dataset.index; //数组下标
    let tag = e.target.dataset.tag ; //字段名称
    let array = this.data.medicineList;
    array[index][tag] = e.detail.value  //赋值
    this.setData({
      medicineList: array
    })},
//获取药单标题
setMedicineTitle(e)
{
  this.data.medicineTitle=e.detail.value;
},
bindTimeChange: function(e) {
  console.log('picker发送选择改变，携带值为', e.detail.value)
  this.setData({
    medicineTime: e.detail.value
  })
},
//建立id
getid(n)
{
    var result = "";
    var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var charactersLength = characters.length;
    for (var i = 0; i < Number(n); i++) {
      result += characters.charAt(
        Math.floor(Math.random() * charactersLength)
      );
    }
    var dat = util.formatDate(new Date());
  let medicinedate=dat.replace(/-/g, "");
  return result+medicinedate;
},
//添加药单记录
addDrugList()
{
  let that=this;
  let id=this.getid(4);
  let time=[];
  time=that.data.medicineTime.split(':');
  let hour=time[0];
  let minute=time[1];
  that.data.drugListRecordid=id;
  that.addMedicine();
    wx.request({
      url:app.globalData.url+'/addDrugList', 
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      data: {
        drugListRecordid:id,
        drugListRecordTime:that.data.medicineTime,
        openid:app.globalData.openid,
        drugListRecordTitle:that.data.medicineTitle,
        hour:hour,
        minute:minute
       },
       method: 'post',
       success: function (res) {
            console.log("成功");
            console.log(res.data);
       },
       fail:function(err){//请求失败之后要做什么
          console.log('请求失败',err);
          }
  })

  
},
//订阅通知消息
getXiaoxi()
  {
    let that=this;
    let temId = 'E5hcsS32U9hqWHtqjocQ5lXOOjOlV97Wc26vNOSBu34' // 小程序配置模板信息-模板ID
wx.getSetting({
	withSubscriptions: true,//是否同时获取用户订阅消息的订阅状态，默认不获取
	success: (res)=> {
		console.log(res)
		if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
			res.subscriptionsSetting.itemSettings[temId] == "reject"){
			//打开设置去设置
			this.openConfirm('检测到您没打开推送权限，是否去设置打开？')
		}else {
			wx.requestSubscribeMessage({
				tmplIds: [temId],
				success: (res)=> {
					if (res[temId] == 'accept'){
            wx.showToast({
              title: '订阅成功！',
              icon:"success"
            })
            that.addDrugList();
					}
				},
				fail: (res)=> { console.info(res) },
			})
		}
	}
})
  },
//添加药单记录
addMedicine(){
  let that=this;
  let mid="";
  let mList=that.data.medicineList;
  for(var i=0;i<mList.length;i++){
    mid=that.getid(5)+i;
    wx.request({
      url:app.globalData.url+'/addMedicine', 
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      data: {
        drugListRecordid:that.data.drugListRecordid,
        medicineid:mid,
        medicineTitle:mList[i]["name"],
        medicineDateOne:mList[i]["frequency"],
        medicineOneTime:mList[i]["particles"],
        openid:app.globalData.openid
       },
       method: 'post',
       success: function (res) {
            console.log("成功");
            console.log(res.data);
       },
       fail:function(err){//请求失败之后要做什么
          console.log('请求失败',err);
    
          }  
  })
  }
  that.goPageList();
},
 //跳转药单列表
 goPageList()
 {
 wx.navigateBack({
   delta: 1,
 })
 },
  onShareAppMessage: function () {

  }
})